<template>
  <div>
    <h2>菜品列表</h2>
    <button @click="router.push('/admin/dishes/add')">添加菜品</button>
    <table>
      <tr><th>名称</th><th>价格</th><th>分类</th><th>操作</th></tr>
      <tr v-for="d in list" :key="d.dishId">
        <td>{{ d.dishName }}</td>
        <td>￥{{ d.price }}</td>
        <td>{{ d.categoryId }}</td>
        <td>
          <button @click="edit(d)">编辑</button>
          <button @click="del(d)">删除</button>
        </td>
      </tr>
    </table>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import service from '@/utils/request.js'

const list = ref([])
const router = useRouter()

async function fetch() {
  const res = await service.get('/menu/dishes')
  list.value = res.data.data.dishes
}

function edit(dish) {
  router.push(`/admin/dishes/edit/${dish.dishId}`)
}

async function del(dish) {
  if (confirm(`确认删除 ${dish.dishName}？`)) {
    await service.delete(`/admin/dishes/${dish.dishId}`)
    alert('删除成功')
    await fetch()
  }
}

onMounted(fetch)
</script>
